package com.rd.student.jike.class2.xuezhixin.leetcode;

public class _160 {

    public static void main(String[] args) {
        ListNode headA1 = new ListNode(1);
        ListNode headA2 = new ListNode(9);
        ListNode headA3 = new ListNode(1);
        ListNode headA4 = new ListNode(2);
        ListNode headA5 = new ListNode(4);

        headA1.next = headA2;
        headA2.next = headA3;
        headA3.next = headA4;
        headA4.next = headA5;

        ListNode headB1 = new ListNode(3);
        ListNode headB2 = new ListNode(2);
        ListNode headB3 = new ListNode(4);
//        ListNode headB4 = new ListNode(2);
//        ListNode headB5 = new ListNode(4);

        headB1.next = headB2;
        headB2.next = headB3;

        Solution160.getIntersectionNode(headA1,headB1);
    }

}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}

class Solution160 {
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int longA = 0;
        int longB = 0;
        ListNode tmpA = headA;
        while (tmpA.next != null) {
            tmpA = tmpA.next;
            longA++;
        }
        ListNode tmpB = headB;
        while (tmpB.next != null) {
            tmpB = tmpB.next;
            longB++;
        }

        tmpA = headA;
        tmpB = headB;

        if (longA > longB) {
            int num = longA - longB;
            for (int i = 0;i<num;i++){
                tmpA = tmpA.next;
            }
            while (tmpA != null) {
                if (tmpA == tmpB){
                    return tmpA;
                }
                tmpA = tmpA.next;
                tmpB = tmpB.next;
            }
            return null;
        }else {
            int num = longB - longA;
            for (int i = 0;i<num;i++){
                tmpB = tmpB.next;
            }
            while (tmpB != null) {
                if (tmpA == tmpB){
                    return tmpB;
                }
                tmpA = tmpA.next;
                tmpB = tmpB.next;
            }
            return null;
        }
    }
}

